package file

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/constants"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"time"
)

type CommonFileRepository struct {
}

func NewFileRepository() CommonFileRepoIface {
	return &CommonFileRepository{}
}
func (r *CommonFileRepository) SaveToFile(ctx context.Context, ossFilePath, fileType, fileName, business string, size int64, isPrivate int64, tenantCode string) (string, error) {
	db := stark.MySQLConn.Get(ctx)
	uid := uuid.New().String()
	commonFilePo := &CommonFilePo{
		FileName:   fileName,
		FilePath:   ossFilePath,
		FileSize:   size,
		FileType:   fileType,
		IsPrivate:  isPrivate,
		Uid:        uid,
		Business:   business,
		TenantCode: tenantCode,
		CreatedOn:  time.Now(),
		CreatedBy:  "",
		ModifiedOn: time.Now(),
		ModifiedBy: "",
		IsDeleted:  constants.IsDeletedFalse,
	}
	err := db.Save(commonFilePo).Error
	if err != nil {
		return "", err
	}
	return uid, nil
}

func (r *CommonFileRepository) QueryByUid(ctx context.Context, fileUid string) (*CommonFilePo, error) {
	var result CommonFilePo
	err := stark.MySQLConn.Get(ctx).Table(result.TableName()).
		Where("is_deleted = ?", constants.IsDeletedFalse).
		Where("uid = ?", fileUid).
		First(&result).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		stark.Logger.Errorf(ctx, "QueryByUid,err:%s", err.Error())
		return nil, err
	}
	return &result, nil
}
